package com.nx.platform.es.bean.modle.agg;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.nx.platform.es.common.utils.MoreMaps;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;

import java.util.Map;

public class AggField {

    private final String face;
    private final AggFieldType type;
    private final ImmutableMap<String, ?> config;

    private AggField(String face, AggFieldType type, ImmutableMap<String, ?> config) {
        this.face = face;
        this.type = type;
        this.config = config;
    }

    public static AggField create(Map<?, ?> settings) {
        String face = MoreMaps.getString(settings, "face");
        Preconditions.checkState(!Strings.isNullOrEmpty(face), "param face empty or null");
        String type = MoreMaps.getString(settings, "type");
        Preconditions.checkState(!Strings.isNullOrEmpty(type), "type not found");
        AggFieldType fieldType = AggFieldType.valueOf(type);
        ImmutableMap<String, ?> config = fieldType.getParser().parse(settings);
        return new AggField(face, fieldType, config);
    }

    public TermsAggregationBuilder handle(Map<String, ?> params) {
        return type.getHandler().handle(config, params);
    }

    public String getFace() {
        return face;
    }

    public AggFieldType getType() {
        return type;
    }

    public ImmutableMap<String, ?> getConfig() {
        return config;
    }

}
